import registerTpl from 'ngtemplate!html!../../../tpls/entry/entry.registerlist.tpl.html';

class EntryRegisterListController {
    constructor($rootScope, $scope, $cookieStore, $timeout, $state, EntryService, ngDialog, dialogService, iRunner, getCourseList){

    	var vm = this;

    	vm.$rootScope    = $rootScope;
    	vm.$cookieStore  = $cookieStore;
    	vm.$timeout 	 = $timeout;
    	vm.$state   	 = $state;
    	vm.ngDialog 	 = ngDialog;
    	vm.dialogService = dialogService;
    	vm.iRunner 	     = iRunner;
        vm.EntryService = EntryService;

        //科目list
        vm.getCourseList = getCourseList.data;
        console.log(vm.getCourseList);

        vm.$timeout( () => { vm.search1(); }, 0);
        

        /**
         * [search1 点击搜索按钮]
         * @return {[type]} [description]
         */
        vm.search1 = function() {
            //清空模板数据
            vm.$timeout( () => { vm.registerTpl = ''; }, 0);
            vm.$timeout( () => { vm.registerTpl = registerTpl; }, 0);           
            //初始化执行搜索功能
            vm.$timeout( () => { vm.search(); }, 0);
        }

        /**
         * [export 导出已报名选手功能]
         * @return {[type]} [description]
         */
        vm.export = function() {
            //导出已报名选手
            vm.window = window.open("/dashboard/register/export?race_id=" + vm.$state.params.race_id + "&access-token=" + this.$cookieStore.get('access_token'));                 
        }
        
        /**
         * [search 搜索功能]
         * @return {[type]} [description]
         */
        vm.search = function() {

            //科目
            var courseId = vm.courseId ? vm.courseId : '';
            
            //选手报名状态
            var paystatus = vm.paystatus ? vm.paystatus : '';

            //选手报名状态
            var verifystatus = vm.verifystatus ? vm.verifystatus : '';

            //选手号
            var name = vm.name ? vm.name : '';

            //加载表格数据
            var tableData = angular.element('#bib_lists_table').DataTable($.extend({}, vm.tableSettings.dataTable, {
                // --- Data (/registerpicknum/lists?race_id=)
                ajax: iRunner.config.baseUrl + '/register/lists?race_id=' + vm.$state.params.race_id + '&access-token=' + this.$cookieStore.get('access_token') + '&course_id=' + courseId + '&paystatus=' + paystatus + '&verifystatus=' + verifystatus + '&passport_name=' + name,
                order: [0, "desc"], // ID 倒序
                // --- Column       
                columns: iRunner.regesterColumns,
                // --- CreatedRow
                createdRow: ( row, data, index ) => {
                    // console.log(data);
                },
                // --- Callback
                initComplete: () => {}
            }));

            // 上下每页条数下拉框同步
            $('.dataTables_length').find('select').on('change', function(event) {
                //清空当前页面数据
                vm.realtimeData = [];
                const select =  $('.dataTables_length').find('select');
                select.val($(this).val())
            });

            //点击审核按钮
            $('#bib_lists_table').on('click', "tbody > tr [data-action='examine']", function() {
                //审核状态（已审核通过：1）
                var status = $(this).data('status') == 'normal' ? 1 : 2;
                vm.ngDialog.open({
                    template: "<p>确定要改变 " + $(this).data('name') +" 选手审核状态吗？<br> 点击确定按钮后，该选手状态将更改！</p><br><button class='btn btn-primary' ng-click='setExamine(" + $(this).data('registerid') + ", " + status + ")'>确定</button>",
                    className: 'ngdialog-theme-default ngdialog-alert',
                    plain: true,
                    scope: $rootScope
                });
            });

            //点击支付状态设置按钮
            $('#bib_lists_table').on('click', "tbody > tr [data-action='pay']", function() {
                console.log($(this).data('paystatus'));
                //支付状态（已支付：1）
                var payStatus = $(this).data('paystatus') == 'paid' ? 1 : 2;
                vm.ngDialog.open({
                    template: "<p>确定要改变 " + $(this).data('name') +" 选手支付状态吗？<br> 点击确定按钮后，该选手状态将更改！</p><br><button class='btn btn-primary' ng-click='setPayStatus(" + $(this).data('registerid') + ", " + payStatus + ")'>确定</button>",
                    className: 'ngdialog-theme-default ngdialog-alert',
                    plain: true,
                    scope: $rootScope
                });
            });

            // 取消报名按钮
            $('#bib_lists_table').on('click', "tbody > tr [data-action='cancel']", function() {
                console.log($(this).data('paystatus'));
                //支付状态（已支付：1）
                var payStatus = $(this).data('paystatus') == 'paid' ? 1 : 2;
                vm.ngDialog.open({
                    template: "<p>确定要取消 " + $(this).data('name') +" 选手报名吗？<br> 点击确定按钮后，将取消该选手报名！</p><br><button class='btn btn-primary' ng-click='cancel(" + $(this).data('registerid') + ")'>确定</button>",
                    className: 'ngdialog-theme-default ngdialog-alert',
                    plain: true,
                    scope: $rootScope
                });
            });



            // 报名选手详情表格配置
            function registerlistShowInfo(obj) {
                console.log(obj);

                let data = obj;

                for(var i in data){
                    if (data.hasOwnProperty(i)) {
                        data[i] = data[i] && data[i] != 0 ? data[i] : '-'
                    }
                }

                var content =  
                    `<table class="table-detail">
                        <tr>
                            <td>地址:</td>
                            <td>${data.address}</td>
                        </tr>
                        <tr>
                            <td>年龄:</td>
                            <td>${data.age}</td>
                        </tr>
                        <tr>
                            <td>血型:</td>
                            <td>${data.blood_type}</td>
                        </tr>
                        <tr>
                            <td>城市:</td>
                            <td>${data.city}</td>
                        </tr>
                        <tr>
                            <td>电子邮箱:</td>
                            <td>${data.email}</td>
                        </tr>
                        <tr>
                            <td>紧急联系人关系:</td>
                            <td>${data.emerge_ship}</td>
                        </tr>
                        <tr>
                            <td>紧急联系人姓名:</td>
                            <td>${data.emerge_name}</td>
                        </tr>
                        <tr>
                            <td>紧急联系人联系方式:</td>
                            <td>${data.emerge_contact}</td>
                        </tr>
                        <tr>
                            <td>国籍:</td>
                            <td>${data.nationality}</td>
                        </tr>
                        <tr>
                            <td>上衣尺码:</td>
                            <td>${data.tshirt}</td>
                        </tr>
                    `;

                for (var i = 1; i <= 22; i++) {
                    if (data['ext_field_' + i].title) {
                        content += `
                            <tr>
                                <td>${data['ext_field_' + i].title}</td>
                                <td>${data['ext_field_' + i].value ? data['ext_field_' + i].value : '-'}</td>
                            </tr>
                        `
                    }
                }

                return content + '</table>';
            }

            $('#bib_lists_table tbody').on('click', 'td.details-control', function (event) {
                event.stopPropagation();
                var tr = $(this).closest('tr');
                var row = tableData.row( tr );
         
                if ( row.child.isShown() ) {
                    // This row is already open - close it
                    row.child.hide();
                    tr.removeClass('shown');
                }
                else {
                    // Open this row
                    row.child( registerlistShowInfo(row.data()) ).show();                    
                    tr.addClass('shown');
                }


            });


        }

        /**
         * [cancel 取消报名]
         * @param  {[type]} value [description]
         * @return {[type]}       [description]
         */
        $rootScope.cancel = function(value) {

            //调用接口，取消选手报名
            vm.EntryService.postRegisterCancel(vm.$cookieStore.get('access_token'), value)
            .then( data => {
                // 成功调用
                data.code==0&&vm.dialogService.success('修改成功');
                // 调用失败, 提示用户
                data.code!=0&&vm.dialogService.error(data.message);
                console.log(data)
            }, error => console.log('error'));
                vm.ngDialog.close();
                // 重新载入页面
                // vm.$state.reload();
        }


        /**
         * [setExamine 设置选手审核状态]
         * @param {[type]} value  [description]
         * @param {[type]} status [description]
         */
        $rootScope.setExamine = function(value, status) {

            var op = status == 1 ? 'refuse' : 'appove';
            //调用接口，将选手审核通过
            vm.EntryService.postRegisterVerify(vm.$cookieStore.get('access_token'), value + '&op=' + op)
            .then( data => {
                // 成功调用
                data.code==0&&vm.dialogService.success('修改成功');
                // 调用失败, 提示用户
                data.code!=0&&vm.dialogService.error(data.message);
                console.log(data)
            }, error => console.log('error'));                    

                vm.ngDialog.close();
                // 重新载入页面
                vm.$state.reload();
        }

        /**
         * [setExamine 设置选手支付状态]
         * @param {[type]} value  [description]
         * @param {[type]} status [description]
         */
        $rootScope.setPayStatus = function(value, status) {

            var op = status == 1 ? 'unpaid' : 'paid';
            //调用接口，将选手审核通过
            vm.EntryService.postRegisterPaystatus(vm.$cookieStore.get('access_token'), value + '&op=' + op)
            .then( data => {
                // 成功调用
                data.code==0&&vm.dialogService.success('修改成功');
                // 调用失败, 提示用户
                data.code!=0&&vm.dialogService.error(data.message);
                console.log(data)
            }, error => console.log('error'));                    

                //关闭确认充值模态框
                vm.ngDialog.close();
                // 重新载入页面
                vm.$state.reload();
        }

        vm.tableSettings = {
            KEYCODE: {
                ENTER: 13,
                DELETE: 46,
                BACKSPACE: 8,
                UP: 38,
                DOWN: 40
            },
            imageTypes: "*.gif;*.jpg;*.jpeg;*.png;",
            dataTable: {

                /*基本参数设置，以下参数设置和默认效果一致*/
                "paginate": true, //翻页功能
                "lengthChange": true, //改变每页显示数据数量
                "filter": true, //过滤功能
                "sort": true, //排序功能
                "info": true,//页脚信息
                "autoWidth": true,//自动宽度
                /*默认排序设置*/
                // "aSorting": [[ 4, "desc" ]],//设置第5个元素为默认排序
                /*默认翻页样式设置*/
                "paginationType": "full_numbers",
                /*是否开启主题*/
                // "jQueryUI": true,
                /*语言设置*/
                "language": {
                    "lengthMenu": "每页显示 _MENU_条",
                    "zeroRecords": "没有找到符合条件的数据",
                    "processing": "加载中...",
                    "info": "当前第 _START_ - _END_ 条　共计 _TOTAL_ 条",
                    "infoEmpty": "没有记录",
                    // "infoFiltered": "(从 _MAX_ 条记录中过滤)",
                    "infoFiltered": "",
                    "search": "搜索：",
                    "paginate": {
                        "first": "首页",
                        "previous": "前一页",
                        "next": "后一页",
                        "last": "尾页"
                    }
                },

                // --- Data
                processing: true,
                serverSide: true,
                // --- Language
                // language: $.extend({}, iRunner.l("DATATABLE"), {
                //     processing: 'Loading...'
                // }),
                // --- Pagination
                pageLength: 50,
                pagingType: "full_numbers",
                lengthMenu: [10, 20, 50, 100, 200],
                // dom: "rt<'page-list-footer'lp>"
                dom: '<"page-list-footer"<br/>lp<"clear">irt<"page-list-footer"lp<"clear">ir'
            }
        }

    }

    
}

EntryRegisterListController.$inject = ['$rootScope', '$scope', '$cookieStore', '$timeout', '$state', 'EntryService', 'ngDialog', 'dialogService', 'iRunner', 'getCourseList']; 

export default EntryRegisterListController;